package org.pettyfox.pfpay.biz;

import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.pettyfox.pfpay.entity.PayAlone;
import org.pettyfox.pfpay.pojo.api.PayAlonePojo;
import org.pettyfox.pfpay.utils.FreeBusyRedisQueue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 个人支付，实时的支付信息、处理
 */
@Service
@Slf4j
public class PayAloneRealPayBiz  {

    @Value("${project.expire-min:10}")
    private int ExpireMin;//锁定支付时间
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    FreeBusyRedisQueue freeBusyRedisQueue;
    @Resource
    PayAloneBiz payAloneBiz;

    /**
     * 将所以支付配置缓存到Redis中
     */
    public synchronized void initQueue(){

        List<PayAlone> listEnable = payAloneBiz.listAllByEnable();
        Map<String,Set<String>> allFreeList = new HashMap<>();
        Optional.ofNullable(listEnable).map(list->{
            list.stream().forEach(p->{
                String key = "uid"+"-"+p.getBehooveAmount()+"-"+p.getType();
                if(allFreeList.containsKey(key)){
                    allFreeList.get(key).add(String.valueOf(p.getId()));
                }else{
                    Set<String> temp = new HashSet<>();
                    temp.add(String.valueOf(p.getId()));
                    allFreeList.put(key,temp);
                }
            });
            return list;
        });
        allFreeList.forEach((k,v)->{
            freeBusyRedisQueue.initQueue(v,k);
        });

    }


    /**
     * 获取支付信息
     * @param uid
     * @param behooveAmount 应付金额
     * @param type
     * @return
     */
    public PayAlonePojo getPayAlone(String uid, BigDecimal behooveAmount, PayAlone.Type type){
        String key = uid+"-"+behooveAmount+"-"+type.value();
        Date expireDate = new DateTime().plusMinutes(ExpireMin).toDate();
        String id = freeBusyRedisQueue.popFreeQueue(key,expireDate);

        if(null != id){
            PayAlone payAlone = payAloneBiz.get(id);
            PayAlonePojo payAlonePojo = new PayAlonePojo();
            payAlonePojo.setExpireDate(expireDate);
            payAlonePojo.setId(payAlone.getId());
            payAlonePojo.setBehooveAmount(payAlone.getBehooveAmount());
            payAlonePojo.setRealAmount(payAlone.getRealAmount());
            payAlonePojo.setType(payAlone.getType());
            payAlonePojo.setPayLink(payAlone.getPayLink());
            return payAlonePojo;
        }
        return null;
    }

    /**
     * 实时支付信息
     * @return
     */
    public Object realPayInfo(){

        return freeBusyRedisQueue.realQueueInfo();
    }
}
